import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Typography,
  Descriptions,
  Statistic,
  Tag,
  Space,
  message,
  Spin,
} from 'antd';
import {
  UserOutlined,
  CloudUploadOutlined,
  CloudDownloadOutlined,
  TrophyOutlined,
  CalendarOutlined,
} from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { getUserProfile } from '../api/user';
import { UserProfileResponse, USER_CLASS_MAP } from '../types';
import { formatBytes, formatDateTime } from '../utils/format';

const { Title, Text } = Typography;

const UserProfile: React.FC = () => {
  const { userId } = useParams<{ userId: string }>();
  const [user, setUser] = useState<UserProfileResponse | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (userId) {
      fetchUserProfile();
    }
  }, [userId]);

  const fetchUserProfile = async () => {
    try {
      setLoading(true);
      const response = await getUserProfile(Number(userId));
      if (response.code === 200) {
        setUser(response.data);
      } else {
        message.error(response.message || '获取用户资料失败');
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
      message.error('获取用户资料失败');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!user) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text>用户不存在</Text>
        </div>
      </Card>
    );
  }

  const userClassInfo = USER_CLASS_MAP[user.userClass as keyof typeof USER_CLASS_MAP];

  return (
    <div>
      <Row gutter={16}>
        {/* 用户基本信息 */}
        <Col span={24}>
          <Card>
            <Row gutter={16} align="middle">
              <Col>
                {user.avatar ? (
                  <img
                    src={`http://localhost:8080${user.avatar}`}
                    alt="用户头像"
                    style={{
                      width: 80,
                      height: 80,
                      borderRadius: '50%',
                      objectFit: 'cover'
                    }}
                    onError={(e) => {
                      // 头像加载失败时显示默认头像
                      (e.target as HTMLImageElement).style.display = 'none';
                      const fallback = document.querySelector('.fallback-avatar') as HTMLElement;
                      if (fallback) {
                        fallback.style.display = 'block';
                      }
                    }}
                  />
                ) : (
                  <Avatar size={80} icon={<UserOutlined />} />
                )}
                {user.avatar && (
                  <Avatar 
                    size={80} 
                    icon={<UserOutlined />} 
                    style={{ display: 'none' }}
                    className="fallback-avatar"
                  />
                )}
              </Col>
              <Col flex="auto">
                <Space direction="vertical" size="small">
                  <Title level={2} style={{ margin: 0 }}>
                    {user.username}
                  </Title>
                  <Space>
                    <Tag color={userClassInfo?.color || 'default'}>
                      <TrophyOutlined /> {userClassInfo?.text || '未知等级'}
                    </Tag>
                    <Text type="secondary">
                      <CalendarOutlined /> 注册时间: {formatDateTime(user.createdTime)}
                    </Text>
                  </Space>
                  <Text type="secondary">
                    上次登录: {user.lastLoginTime ? formatDateTime(user.lastLoginTime) : '从未登录'}
                  </Text>
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        {/* 统计信息 */}
        <Col span={24}>
          <Card title="统计信息">
            <Row gutter={16}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="上传量"
                    value={formatBytes(user.uploaded)}
                    prefix={<CloudUploadOutlined style={{ color: '#52c41a' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="下载量"
                    value={formatBytes(user.downloaded)}
                    prefix={<CloudDownloadOutlined style={{ color: '#1890ff' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="分享率"
                    value={user.shareRatio.toFixed(2)}
                    prefix={<TrophyOutlined style={{ color: '#fa8c16' }} />}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="魔力值"
                    value={user.bonusPoints}
                    prefix={<TrophyOutlined style={{ color: '#eb2f96' }} />}
                  />
                </Card>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        {/* 详细信息 */}
        <Col span={24}>
          <Card title="详细信息">
            <Descriptions column={2} bordered>
              <Descriptions.Item label="用户ID">{user.id}</Descriptions.Item>
              <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
              <Descriptions.Item label="等级">
                <Tag color={userClassInfo?.color}>{userClassInfo?.text}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {formatDateTime(user.createdTime)}
              </Descriptions.Item>
              <Descriptions.Item label="上次登录">
                {user.lastLoginTime ? formatDateTime(user.lastLoginTime) : '从未登录'}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default UserProfile; 